package edu.njust.httpmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.njust.httpmanager.constance.UserAuth;
import edu.njust.httpmanager.entity.Api;
import edu.njust.httpmanager.entity.Catalog;
import edu.njust.httpmanager.entity.Program;
import edu.njust.httpmanager.entity.ProgramMember;
import edu.njust.httpmanager.entity.dto.ProgramDto;
import edu.njust.httpmanager.mapper.ApiMapper;
import edu.njust.httpmanager.mapper.CatalogMapper;
import edu.njust.httpmanager.mapper.ProgramMapper;
import edu.njust.httpmanager.service.IProgramMemberService;
import edu.njust.httpmanager.service.IProgramService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProgramServiceImpl extends ServiceImpl<ProgramMapper, Program> implements IProgramService {

    @Resource
    private IProgramMemberService programMemberService;

    @Resource
    private CatalogMapper catalogMapper;

    @Resource
    private ApiMapper apiMapper;

    @Override
    @Transactional  // 多表操作，开启事务
    public void saveWithAuth(Program program, Long userId) {

        // 存储项目
        this.save(program);
        Long programId = program.getId();

        ProgramMember member = new ProgramMember();
        member.setUserId(userId);
        member.setProgramId(programId);
        member.setUserRole(UserAuth.ADMIN);
        programMemberService.save(member);
    }

    @Override
    public List<ProgramDto> getUserProgramWithAuth(Long userId) {
        return baseMapper.getUserProgramWithAuth(userId);
    }

    @Override
    @Transactional  // 涉及多表增删改开启事务管理
    public void deleteProgram(Long id) {
        // 从项目表中删除
        this.removeById(id);

        // 从成员表中删除
        LambdaQueryWrapper<ProgramMember> memberWrapper = new LambdaQueryWrapper<>();
        memberWrapper.eq(ProgramMember::getProgramId, id);
        programMemberService.remove(memberWrapper);

        // 从目录表中删除
        LambdaQueryWrapper<Catalog> catalogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        catalogLambdaQueryWrapper.eq(Catalog::getProgramId, id);
        catalogMapper.delete(catalogLambdaQueryWrapper);

        // 从接口表中删除
        LambdaQueryWrapper<Api> apiLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apiLambdaQueryWrapper.eq(Api::getProgramId, id);
        apiMapper.delete(apiLambdaQueryWrapper);

    }

    @Override
    public ProgramDto getUserProgramWithAuthById(Long userId, Long programId) {
        return baseMapper.getUserProgramWithAuthById(userId, programId);
    }
    public List<ProgramDto> getUserProgramWithName(Long userId,String programName){
        return baseMapper.getUserProgramWithName(userId, programName);
    }
}
